package club.banyuan.SpringBootThymeleaf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class LoginController {
    @GetMapping("/")
    public String index() {
        return "login";
    }

    @PostMapping("/login")
    public String login(String username, String password, Model model, RedirectAttributes redirectAttributes) {
        if (verify(username,password)) {
            redirectAttributes.addFlashAttribute("username",username);
            // 重定向
            // 不加redirect 就相当于转发
            return "redirect:/home_page";
        }else {
            // 添加属性 页面可以直接得到
            model.addAttribute("message","Login Error!");
            return "login";
        }
    }

    @GetMapping("/home_page")
    public ModelAndView homepage(@ModelAttribute("username") String username) {
        return new ModelAndView("home_page");
//        return "home_page";
    }

    private boolean verify(String username, String password) {
        return "admin".equals(username) && "123456".equals(password);
    }
}
